<!--
 * @Author: deliteam 462085920@qq.com
 * @Date: 2023-12-13 16:57:04
 * @Description: 
-->

<template>
    <div class="back-top" :class="{ 'in': isTop }" @click="scrollTop(300)">
        <img src="/icons/back-top.png" alt="">
    </div>
</template>

<script setup>
const isTop = ref(false);
onMounted(() => {
    // 调用jquery
    // if(window.$){
    //     console.log('[ window.$ ] >', window.$)
    // }
    const checkScroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        isTop.value = scrollTop > 500;
    };
    window.addEventListener("scroll", checkScroll);
});

const scrollTop = (duration) => {
    const totalScrollDistance = window.pageYOffset;
    let scrollY = totalScrollDistance, oldTimestamp = null;
    function step(newTimestamp) {
        if (oldTimestamp !== null) {
            // 计算时间差
            const delta = newTimestamp - oldTimestamp;
            // 修改滚动距离
            scrollY -= totalScrollDistance * (delta / duration);
            if (scrollY <= 0) return window.scrollTo(0, 0);
            window.scrollTo(0, scrollY);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);

    // window.scrollTo({
    //     top: 0,
    //     behavior: 'smooth'
    // });
}
</script>

<style scss="scss" scoped>
.back-top {
    width: 100px;
    position: fixed;
    right: 25px;
    bottom: 20vh;
    z-index: 88;
    opacity: 0;
    transition: all 0.3s linear;
    cursor: pointer;
    transform: scale(0);
}

.back-top.in {
    opacity: 1;
    transform: scale(1);
}

.back-top:hover {
    box-shadow: 0px 4px 10px rgba(41, 41, 41, 0.2);
}

@media screen and (max-width: 768px) {
    .back-top {
        width: 60px;
        right: 5px;
        box-shadow: 0px 4px 10px rgba(41, 41, 41, 0.2);
    }
}
</style>

